package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.cache.TsCache;
import com.atguigu.tingshu.model.album.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.reactive.TransactionalOperator;





import java.util.*;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;


	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;

//    @Autowired
//    private TransactionalOperator transactionalOperator;


	@Override
	public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {

		List<Long> category2IdList = baseCategory2Mapper.selectList(new LambdaQueryWrapper<BaseCategory2>().eq(BaseCategory2::getCategory1Id, category1Id)).stream().map(BaseCategory2::getId).collect(Collectors.toList());
		List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(new LambdaQueryWrapper<BaseCategory3>().in(BaseCategory3::getCategory2Id, category2IdList).eq(BaseCategory3::getIsTop, 1).last("limit 7"));
		return baseCategory3List;

	}

	@Override
	@TsCache(prefix = "category:")
	public BaseCategoryView getCategoryView(Long category3Id) {
		return baseCategoryViewMapper.selectById(category3Id);
	}

	@Override
	/**
	 * 根据一级分类ID获取分类基础列表
	 * 
	 * @param category1Id 一级分类ID
	 * @return 包含一级分类及其子分类的JSONObject
	 */
	public JSONObject getBaseCategoryList(Long category1Id) {
	    // 创建一个JSONObject对象来存储一级分类信息
	    JSONObject category1 = new JSONObject();
	    // 将一级分类ID存入JSONObject
	    category1.put("categoryId",category1Id);
	
	    // 查询属于该一级分类的所有基础分类视图
	    List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(new LambdaQueryWrapper<BaseCategoryView>().eq
	            (BaseCategoryView::getCategory1Id, category1Id));
	
	    // 获取一级分类名称
	    String category1Name = baseCategory1Mapper.selectById(category1Id).getName();
	
	    // 将一级分类名称存入JSONObject
	    category1.put("categoryName",baseCategoryViewList.get(0).getCategory1Name());
	    // 获取二级分类数据
	    Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
	    Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category2Map.entrySet().iterator();
	
	    // 创建一个ArrayList来存储二级分类的JSONObject对象
	    ArrayList<JSONObject> categoryChild2List = new ArrayList<>();
	
	    // 遍历二级分类Map
	    while (iterator.hasNext()){
	        Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
	        Long category2Id = entry.getKey();
	        List<BaseCategoryView> categoryViewList = entry.getValue();
	        // 创建一个JSONObject对象来存储二级分类信息
	        JSONObject category2 = new JSONObject();
	        // 将二级分类ID存入JSONObject
	        category2.put("categoryId",category2Id);
	        // 将二级分类名称存入JSONObject
	        category2.put("categotyName",categoryViewList.get(0).getCategory2Name());
	
	        // 将三级分类数据转换为JSONObject列表
	        List<JSONObject> list = categoryViewList.stream().map(categoryView -> {
	            JSONObject category3 = new JSONObject();
	            // 将三级分类ID存入JSONObject
	            category3.put("categoryId", categoryView.getCategory3Id());
	            // 将三级分类名称存入JSONObject
	            category3.put("catrgoryName", categoryView.getCategory3Name());
	            return category3;
	        }).collect(Collectors.toList());
	        
	        // 将三级分类列表存入二级分类的JSONObject
	        category2.put("categoryChild",list);
	
	        // 将二级分类的JSONObject添加到列表中
	        categoryChild2List.add(category2);
	    }
	    // 将二级分类集合存入一级分类的JSONObject
	    category1.put("categoryChild","二级分类集合");
	
	    // 返回包含一级分类及其子分类信息的JSONObject
	    return category1;
	}

	@Override
	public List<BaseAttribute> findAttribute(Long category1Id) {
		//	调用mapper 层
		//	UserMapper userMapper = sqlsession.getMapper(UserMapper)  userMapper.getAll();
		return baseAttributeMapper.selectAttribute(category1Id);
	}




	@Override
	public List<JSONObject> getBaseCategoryList() {
		//创建一个空的JSON对象列表
		ArrayList<JSONObject> list = new ArrayList<>();
		//获取所有分类数据; select * from base_category_view where is_delete = 0;
		List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
		//设置一个map 集合 ，key=category1Id value=List<BaseCategoryView>
		Map<Long, List<BaseCategoryView>> categoryMap = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
		// 循环遍历集合
		Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = categoryMap.entrySet().iterator();
		while (iterator.hasNext()) {
			// 获取元素
			Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
			// 获取一级分类Id
			Long category1Id = entry.getKey();
			// 获取一级分类名称
			String category1Name = entry.getValue().get(0).getCategory1Name();
			// 构建数据：
			JSONObject category1 = new JSONObject();
			category1.put("categoryId",category1Id);
			category1.put("categoryName",category1Name);
			// 获取二级分类数据; 以二级分类Id 当做key 进行分组； key = category2Id value=List<BaseCategoryView>
			Map<Long, List<BaseCategoryView>> category2Map = entry.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
			Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category2Map.entrySet().iterator();
			// 创建一个集合
			ArrayList<JSONObject> category2Child = new ArrayList<>();
			while (iterator1.hasNext()){
				// 获取对象数据
				Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
				// 获取二级分类Id
				Long category2Id = entry1.getKey();
				// 获取二级分类名称
				String category2Name = entry1.getValue().get(0).getCategory2Name();
				// 构建二级对象
				JSONObject category2 = new JSONObject();
				category2.put("categoryId",category2Id);
				category2.put("categoryName",category2Name);
				// 获取到三级分类集合; 循环遍历二级分类value 中的数据，将三级分类Id，name添加到一个集合中！
				// 创建一个集合
				// ArrayList<JSONObject> category3Child = new ArrayList<>();
				// for (BaseCategoryView baseCategoryView : entry1.getValue()) {
				//     Long category3Id = baseCategoryView.getCategory3Id();
				//     String category3Name = baseCategoryView.getCategory3Name();
				//     // 创建三级分类对象
				//     JSONObject category3 = new JSONObject();
				//     category3.put("categoryId",category3Id);
				//     category3.put("categoryName",category3Name);
				//     category3Child.add(category3);
				// }
				// map 做映射处理！ 循环遍历集合数据，并取出数据再组成新的集合；那么就可以使用stream().map(); 复制小括号（一个参数括号可以省略），写死右箭头，落地大括号
				List<JSONObject> category3Child = entry1.getValue().stream().map(baseCategoryView -> {
					// 创建三级分类对象
					JSONObject category3 = new JSONObject();
					category3.put("categoryId", baseCategoryView.getCategory3Id());
					category3.put("categoryName", baseCategoryView.getCategory3Name());
					// 返回数据
					return category3;
				}).collect(Collectors.toList());
				category2.put("categoryChild",category3Child);
				// 将所有的二级分类对象添加到集合中
				category2Child.add(category2);
			}
			// 将一级分类数据添加到集合中
			category1.put("categoryChild",category2Child);
			list.add(category1);
		}
		// 返回数据
		return list;

	}

}
